﻿using AutoMapper;
using CSRedis;
using EMS.system.Common;
using EMS.system.Entityies.MasterData.UnitMeasureModel;
using EMS.system.Entityies.MasterData.WorkstationModel;
using EMS.system.IEntityAppService.MasterData.UnitMeasureService;
using EMS.system.IEntityAppService.MasterData.UnitMeasureService.UnitMeasureDTOs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Entities;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace EMS.system.EntityAppService.MasterData.UnitMeasureService
{
    public class UnitMeasureAppService : ApplicationService, IUnitMeasureAppService
    {
        //private static Object obj=new Object();
        //private readonly CSRedisClient _client = new CSRedisClient("localhost:6379");

        /// <summary>
        /// 计量单位仓储
        /// </summary>
        private readonly IRepository<UnitMeasure, int> _unitMeasurerepository;
        public UnitMeasureAppService(IRepository<UnitMeasure, int> unitMeasurerepository)
        {
            _unitMeasurerepository = unitMeasurerepository;
        }
        /// <summary>
        /// 获取计量单位列表 分页
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="unitMeasureCode"></param>
        /// <param name="unitMeasureName"></param>
        /// <returns></returns>
       
        public async Task<PagedResult> GetUnitMeasureList(int pageIndex, int pageSize, string? unitMeasureCode, string? unitMeasureName)
        {
            var predicate = PredicateBuilder.New<UnitMeasure>(true);
            if (!string.IsNullOrEmpty(unitMeasureCode))
            {
                predicate = predicate.And(m => m.UnitMeasureCode.Contains(unitMeasureCode));
            }
            if (!string.IsNullOrEmpty(unitMeasureName))
            {
                predicate = predicate.And(m => m.UnitMeasureName.Contains(unitMeasureName));
            }
           
            var dto = await _unitMeasurerepository.GetListAsync(predicate);
            PagedResult result = new PagedResult();
            result.PageCount = (int)Math.Ceiling((decimal)(dto.Count == 0 ? 1 : dto.Count) / pageSize);
            result.PageSize = pageSize;
            result.CurrentPage = pageIndex;
            result.RowCount = dto.Count;
            result.Queryable = dto.Skip((pageIndex - 1) * pageSize).Take(pageSize).AsQueryable();
            return result;
        }
        /// <summary>
        /// 添加计量单位
        /// </summary>
        /// <param name="unitMeasureDTO"></param>
        /// <returns></returns>
        public async Task<int>  CreateUnitMeasure(UnitMeasureDTO unitMeasureDTO)
        {
          
            var unitMeasureCode = _unitMeasurerepository.CountAsync(x => x.UnitMeasureCode == unitMeasureDTO.UnitMeasureCode).Result;
            if(unitMeasureCode > 0)
            {
                return -1;
            }
            var unitMeasureName = _unitMeasurerepository.CountAsync(x => x.UnitMeasureName == unitMeasureDTO.UnitMeasureName).Result;
            if (unitMeasureName > 0)
            {
                return -2;
            }
            var unitMeasure= unitMeasureDTO.MapTo<UnitMeasure>();
            await _unitMeasurerepository.InsertAsync(unitMeasure);
            return 1;
        }
        /// <summary>
        /// 获取计量单位列表
        /// </summary>
        /// <param name="isPrimaryUnit"></param>
        /// <returns></returns>
        public async Task<List< UnitMeasureDTO>> GetUnitMeasure(bool isPrimaryUnit = true)
        {
          
            var unitMeasure = await _unitMeasurerepository.GetListAsync(x=>x.IsPrimaryUnit==isPrimaryUnit);
            var unitMeasureDTO = unitMeasure.MapToList<UnitMeasureDTO>();
            return unitMeasureDTO;
        }
        ///// <summary>
        ///// Redis集群
        ///// </summary>
        ///// <param name = "isPrimaryUnit" ></ param >
        ///// < returns ></ returns >
        ////缓存击穿 （lock锁+2次判断）
        //public async Task<List<UnitMeasureDTO>> GetUnitMeasureRedis(bool isPrimaryUnit = true)
        //{
        //    //根据Key值，获取计量单位list集合
        //    var unitMeasureList = EMS.system.Common.RedisHelper.Get<List<UnitMeasureDTO>>("unitMeasureListKey");
        //    if (unitMeasureList == null)
        //    {
        //        lock (obj)
        //        {
        //            if (unitMeasureList == null)
        //            {
        //                //从数据库中取出计量单位集合
        //                unitMeasureList = GetUnitMeasure(isPrimaryUnit).Result;
        //                var seconds = 30000 + new Random().Next(1, 1000);
        //                //将计量单位集合缓存在Redis中，key值为：unitMeasureList
        //                EMS.system.Common.RedisHelper.Set("unitMeasureListKey", unitMeasureList, DateTime.Now.AddDays(1));
        //            }
        //        }
        //    }
        //    return unitMeasureList;
        //}

        /// <summary>
        /// 删除计量单位
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task< int> DeleteUnitMeasure(string ids)
        {
            string[] arry = ids.Split(',');
            await _unitMeasurerepository.DeleteAsync(x=> ids.Contains(x.Id.ToString()));
            return 1;
        }
        /// <summary>
        /// 获取计量单位主键Id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task< UnitMeasureDTO> GetUnitMeasureById(int id)
        {

          
            var unitMeasure = await _unitMeasurerepository.GetAsync(id);
            var unitMeasureDTO = unitMeasure.MapTo<UnitMeasureDTO>();
            return unitMeasureDTO;
        }
        /// <summary>
        /// 更新计量单位
        /// </summary>
        /// <param name="unitMeasure"></param>
        /// <returns></returns>
        public async Task<int> UpdateUnitMeasure(UnitMeasureDTO  unitMeasureDTO)
        {

            var unitMeasureCode = _unitMeasurerepository.CountAsync(x => x.UnitMeasureCode == unitMeasureDTO.UnitMeasureCode && x.Id != unitMeasureDTO.Id).Result;
            if (unitMeasureCode > 0)
            {
                return -1;
            }
            var unitMeasureName = _unitMeasurerepository.CountAsync(x => x.UnitMeasureName == unitMeasureDTO.UnitMeasureName && x.Id != unitMeasureDTO.Id).Result;
            if (unitMeasureName > 0)
            {
                return -2;
            }
            var unitMeasure = unitMeasureDTO.MapTo< UnitMeasure>();
            await _unitMeasurerepository.UpdateAsync(unitMeasure);
            return 1;

        }
    }
}
